import { fileUrl } from '@/config/env'
import { urlReg } from '@/utils/validate'
import { templatesUrl } from '@/config/env.js'

export const loadStyle = url => {
  const link = document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  link.href = url
  const head = document.getElementsByTagName('head')[0]
  head.appendChild(link)
}

/**
 *解析身份证的出生日期和性别
 * @param {身份证号} card
  */
export function getIdCardInfo(card) {
  const birthday = card.substring(6, 10) + '-' + card.substring(10, 12) + '-' + card.substring(12, 14)
  const sex = parseInt(card.substr(16, 1)) % 2 === 1 ? 1 : 2
  return { birthday, sex }
}
/**
 * 根据出生日期计算年龄
 * @param {出生日期} birthday
 */
export function getAgebyBirthday(birthday) {
  var year = parseInt(renderTime(birthday, '{y}') || 0)
  return year === 0 ? 0 : parseInt(renderTime(new Date(), '{y}')) - parseInt(renderTime(birthday, '{y}'))
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @param {number} 多加多长时间
 * @returns {string}
 */
export function renderTime(time, cFormat) {
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  const date = parseDate(time)
  if (!date) {
    return null
  }

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate() || 0,
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  const date = parseDate(time)
  if (!date) {
    return null
  }
  const d = new Date(date)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return renderTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * 获取两个时间的时间差
 * @param {开始时间} firsttime
 * @param {最后时间} lasttime
 * @param {返回值单位(f:毫秒 s:秒【默认】 m:分钟 h:小时 d:天)} option
 */
export function timeDiff(firsttime, lasttime, option) {
  option = option || 's'
  const date1 = parseDate(firsttime)
  const date2 = parseDate(lasttime)
  if (date1 && date2) {
    let diff = Math.ceil(date2 - date1)
    if (option === 'f') { return diff }
    diff = Math.ceil(diff / 1000)
    if (option === 's') { return diff }
    diff = Math.ceil(diff / 60)
    if (option === 'm') { return diff }
    diff = Math.ceil(diff / 60)
    if (option === 'h') { return diff }
    diff = Math.ceil(diff / 24)
    if (option === 'd') { return diff } else { return undefined }
  } else {
    return undefined
  }
}

/**
 * 将各种格式的日期转换成js识别的时间
 * @param {*} time
 */
export function parseDate(time) {
  if (!time) { return undefined }
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  return date
}

/**
 * 将中文根据首字母排序
 * 返回的数据[{"letter":"a","data":["啊","爱","按"]},{"letter":"b","data":["不"]}]
 */
export function pySegSort(arr) {
  if (!String.prototype.localeCompare) { return null }
  var letters = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('')
  var zh = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀'.split('')
  var arrList = deepClone(arr)
  var result = []
  var curr
  for (var i = 0; i < letters.length; i++) {
    curr = {
      letter: letters[i],
      data: []
    }
    var thislist = []
    for (var j = 0; j < arrList.length; j++) {
      var initial = arrList[j].charAt(0) // 截取第一个字符
      if (arrList[j].charAt(0) === letters[i] || arrList[j].charAt(0) === letters[i].toLowerCase()) { // 首字符是英文的
        curr.data.push(arrList[j])
        thislist.push(j)
      } else if (zh[i] !== '*' && isChinese(initial)) { // 判断是否是无汉字,是否是中文
        if (initial.localeCompare(zh[i]) >= 0 && (!zh[i + 1] || initial.localeCompare(zh[i + 1]) < 0)) { // 判断中文字符在哪一个类别
          curr.data.push(arrList[j])
          thislist.push(j)
        }
      }
    }
    arrList = arrList.filter((item, index) => thislist.indexOf(index) < 0)
    result.push(curr)
  }
  if (arrList.length > 0) {
    result.push({
      letter: '#',
      data: arrList
    })
  }
  return result
}

/**
 * 是否是中文
 * @param {} temp
 */
function isChinese(temp) {
  var re = /[^\u4E00-\u9FA5]/
  if (re.test(temp)) {
    return false
  }
  return true
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * 将字符串转换成base64
 */
export function encode(str) {
  var encode = encodeURI(str)
  var base64 = btoa(encode)
  return base64
}

/**
 * 将base64换成字符串
 */
export function decode(base64) {
  var decode = atob(base64)
  var str = decodeURI(decode)
  return str
}

/**
 * 获取图片（将又拍云与其他地方的地址做区分）
 * @param {*} imageUrl
 * @param {*} parament
 */
export function getImage(imageUrl, parament, noneimg) {
  noneimg = noneimg || 'default'
  const errimages = [
    { type: 'default', url: 'http://file.jiaoxin-tech.cn/yilianyi/none/noimage.png' }
  ]
  console.log(imageUrl, /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i.test(imageUrl || ''))
  if (urlReg.test(imageUrl || '')) {
    if (imageUrl.split('.').slice(-1)[0] !== 'svg' && fileUrl.split('/')[2] === imageUrl.split('/')[2]) { return imageUrl + `${parament ? '!' + parament : ''}` } else { return imageUrl }
  } else {
    return errimages.find(item => item.type === noneimg).url + `${parament ? '!' + parament : ''}`
  }
}

/**
 * 获取地址（将外链、内链、空链进行转换）
 * @param {*} url
 */
export function getLink(url) {
  if (urlReg.test(url)) {
    if (location.host === url.split('/')[2]) {
      const urlnew = url.split('/')
      urlnew.splice(0, 3)
      return `/${urlnew.join('/')}`
    }
    return encode(url)
  }
  return url || 'javascript:'
}

/**
 * 打印区域为局部取域
 */
export function doPrint() {
  const bdhtml = window.document.body.innerHTML
  const sprnstr = '<!--startprint-->'
  const eprnstr = '<!--endprint-->'
  let prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17)
  prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr))
  window.document.body.innerHTML = prnhtml
  window.print()
}

/**
 * 获取站点模板的图片的url
 * id:templateId
 * type:0.非客户模板  1.客户模板
 */

export function getTempalteUrl(id, type) {
  if (type === 1) {
    return templatesUrl + '/static/templates/客户实例' + id + '.jpg'
  } else {
    if (id.length !== 6) {
      return templatesUrl + '/static/templates/精品模版' + id + '.jpg'
    } else {
      return templatesUrl + '/static/templates/' + id + '.jpg'
    }
  }
}

/**
 * 将英文','转换为中文'，' 然后判断是否存在 中文','
 */

export function getDouHao(newValue, type) {
  if (typeof (type) === 'object') {
    if (typeof (type) !== 'string') {
      if (type instanceof Array) {
        if (newValue !== '' && newValue.indexOf(',') !== -1) {
          newValue = newValue.replace(/,/g, '，')
        }
        if (newValue !== '' && newValue.indexOf('，') !== -1) {
          return newValue.split('，')
        } else if (newValue === '') {
          return []
        } else if (newValue !== '' && newValue.indexOf('，') === -1) {
          return [newValue]
        }
      }
      return new Error('类型错误')
    } else if (typeof (type) === 'string') {
      if (newValue !== '' && newValue.indexOf(',') !== -1) {
        newValue = newValue.replace(/,/g, '，')
      }
      if (newValue !== '' && newValue.indexOf('，') !== -1) {
        newValue = newValue.split('，')
        const newArr = []
        for (let i = 0; i < newValue.length; i++) {
          newArr.push({
            key: i,
            value: newValue[i]
          })
        }
        return newArr
      } else if (newValue === '') {
        return {}
      } else if (newValue !== '' && newValue.indexOf('，') === -1) {
        return { key: 1, value: newValue }
      }
    }
  } else {
    return new Error('类型错误')
  }
}

/**
 * 将多层多谢过滤成需要的 [{label:'苹果',value:'1',children:[{  value: 3, label: '普陀' },]}]
 * 原数据机构  [
        {
            "gid":"1",
            "name": "分类1",
            "children": [
                {
                    "gid":"2",
                    "name": "分类2",
                    "children": [
                        {
                            "gid":"3",
                            "name": "分类3",
                        }
                    ]
                }
            ]
        }
    ],
 */
export function getCascader(data) {
  if (!data || !(data instanceof Array)) {
    throw new Error('error arguments', 'getCascader')
  }
  function newMap(data) {
    const arr = []
    data.forEach((item) => {
      if (item.isShow) {
        if (item.children && item.children.length > 0) {
          arr.push({
            'value': item.gid,
            'label': item.name,
            'children': newMap(item.children)
          })
        } else {
          arr.push({
            'value': item.gid,
            'label': item.name
          })
        }
      } else {
        if (item.children && item.children.length > 0) {
          newMap(item.children)
        }
      }
    })
    return arr
  }
  return newMap(data)
}
